﻿using Autodesk.AutoCAD.DatabaseServices;
using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using Aspose.CAD;
using Aspose.CAD.ImageOptions;
using Image = Aspose.CAD.Image;


namespace HaierCADplug_in.View
{
    /// <summary>
    /// TestWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestWindow : Window
    {
        public TestWindow()
        {
            InitializeComponent();
            LoadImg("D:\\Leaning\\Picture");

        }

        public ObservableCollection<ImageData> Images { get; set; } = new ObservableCollection<ImageData>();

        public void LoadImg(string path)
        {

            var imageFiles = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly)
                                     .Where(s => s.EndsWith(".dwg"));

            foreach (var file in imageFiles)
            {


                var bitmap = get_image_of_file(file);

                IntPtr hBitmap = bitmap.GetHbitmap();

                try
                {
                    BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                        hBitmap,
                        IntPtr.Zero,
                        System.Windows.Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                    picImg1.Source = bitmapSource;


                }
                catch { }
            }
        }
        public Bitmap get_image_of_file(string filename)
        {
            //create a new database instance and load the dwg file into it.
            Database dbb = new Database(false, true);
            dbb.ReadDwgFile(filename, FileShare.Read, false, "");

            //grab the thumbnail bitmap and get rid of the white background
            Bitmap preview = dbb.ThumbnailBitmap;
            preview.MakeTransparent(System.Drawing.Color.White);

            return preview;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        public void ConvertDwgToImageAndDisplay(string dwgFilePath)
        {
            // 设置输出图像的路径
            string outputFilePath = System.IO.Path.ChangeExtension(dwgFilePath, ".png");

            // 使用Aspose.CAD转换DWG文件
            using (var image = Aspose.CAD.Image.Load(dwgFilePath))  // 确保正确使用命名空间
            {
                var options = new Aspose.CAD.ImageOptions.PngOptions();  // 确保使用正确的命名空间
                image.Save(outputFilePath, options);
            }

            // 在WPF中显示转换后的图像
            Dispatcher.Invoke(() =>
            {
                BitmapImage bitmap = new BitmapImage(new Uri(outputFilePath, UriKind.Absolute));
                picImg1.Source = bitmap; // 使用正确的控件名
            });
        }
    }
}
